// 防止多次点击跳转（函数节流）
function throttle(fn, gapTime) {
  if (gapTime === null || gapTime === undefined) {
    gapTime = 1500
  }
  let _lastTime = null
  // 返回新的函数
  return function () {
    let _nowTime = +new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments) // 将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}

// 数据转化
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
/**
 * 时间戳转化为年 月 日 时 分 秒
 * number: 传入时间戳
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致
 */
function formatTime(number, format = 'Y/M/D h:m:s') {
  try {
    var formateArr = ['Y', 'M', 'D', 'h', 'm', 's']
    var returnArr = []
    let tempTims = number.toString().length === 13 ? number : number * 1000
    if (!number) {
      return 0
    }
    var date = new Date(tempTims)
    // date.toLocaleString()
    returnArr.push(date.getFullYear())
    returnArr.push(date.getMonth() + 1)
    returnArr.push(date.getDate())
    returnArr.push(formatNumber(date.getHours()))
    returnArr.push(formatNumber(date.getMinutes()))
    returnArr.push(formatNumber(date.getSeconds()))
    for (var i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i])
    }
    return format
  } catch (error) {}
}

function formatDay(number) {
  if (!number) {
    return 0
  }
  const arr = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  const weekDay = new Date(number).getDay()
  return arr[weekDay]
}

/**
 * 转px
 */
function remConvertToPx(remValue) {
  if (typeof remValue === 'string') {
    remValue = parseFloat(remValue.toString().toLocaleLowerCase().replace('rem', ''))
  }
  let htmlPx = parseFloat(
    document.documentElement.style.fontSize.toLocaleLowerCase().replace('px', '')
  )
  return remValue * htmlPx
}

export default {
  throttle,
  formatTime,
  formatDay,
  remConvertToPx
}
